package com.comita.selenium;

import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;

import org.testng.*;
import org.testng.annotations.*;

import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;

import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;

import com.comita.selenium.model.User;

public class Login extends com.comita.selenium.pages.TestBase {
  private boolean acceptNextAlert = true;
  private StringBuffer verificationErrors = new StringBuffer();

  @BeforeMethod
  public void mayBeLogOut(){
	  if (app.getUserHelper().isLoggedIn()) {
		  app.getUserHelper().logout();
	  }
  }
  
  @Test
  public void testLoginOK(){
	  User user = new User().setLogin("admin").setPassword("admin");
	  app.getUserHelper().loginAs(user);
	  assertTrue(app.getUserHelper().isLoggedInAs(user));
  }
  
  @Test
  public void testLogin() throws Exception {
    driver.get(baseUrl + "/php4dvd/");
    wait.until(ExpectedConditions.elementToBeClickable(By.id("username")));
    driver.findElement(By.id("username")).clear();
    driver.findElement(By.id("username")).sendKeys("admin");    
    driver.findElement(By.name("password")).clear();
    driver.findElement(By.name("password")).sendKeys("admin");
    wait.until(ExpectedConditions.elementToBeClickable(By.name("submit")));
    driver.findElement(By.name("submit")).click();
    wait.until(ExpectedConditions.elementToBeClickable(By.id("q")));
    assertTrue(isElementPresent(By.id("q")));
  }

  private boolean isElementPresent(By by) {
    try {
      driver.findElement(by);
      return true;
    } catch (NoSuchElementException e) {
      return false;
    }
  }

  private String closeAlertAndGetItsText() {
    try {
      Alert alert = driver.switchTo().alert();
      String alertText = alert.getText();
      if (acceptNextAlert) {
        alert.accept();
      } else {
        alert.dismiss();
      }
      return alertText;
    } finally {
      acceptNextAlert = true;
    }
  }
}
